const { koaBody } = require("koa-body");
const passport = require("koa-passport");
const session = require("koa-session");
const cors = require("koa2-cors");
const logger = require("../utils/logger.js");
const { userAgent } = require('koa-useragent');

module.exports = (app) => {
  // 注册中间件
  app.use(async (ctx, next) => {
    const start = new Date(); // 响应开始时间
    let intervals; // 响应间隔时间
    try {
      await next();
      intervals = new Date() - start;
      logger.logResponse(ctx, intervals); //记录响应日志
    } catch (error) {
      intervals = new Date() - start;
      console.log("intervals", intervals);
      logger.logError(ctx, error, intervals); //记录异常日志
    }
  });
  app.use(
    koaBody({
      multipart: true,
      strict: false, //设为false
      formidable: {
        maxFileSize: 200 * 1024 * 1024,
      },
    })
  );
  // 初始化 passport
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(userAgent);
  // 回调到utils文件中 passport.js
  require("../utils/passport")(passport);
  app.use(
    cors({
      origin: function (ctx) {
        //   if (ctx.url === "/test") {
        //     return "*"; // 允许来自所有域名请求
        //   }
        //   return "http://localhost:8080"; // 这样就能只允许 http://localhost:8080 这个域名的请求了
        ctx.set("Access-Control-Allow-Origin", "*");
      },
      exposeHeaders: [],
      maxAge: 5,
      credentials: true,
      // 设置所允许的HTTP请求方法
      allowMethods: ["GET", "POST", "DELETE", "PUT"],
      allowHeaders: ["Content-Type", "Authorization", "Accept"],
    })
  );
  /**
   * 在 Nginx 反向代理配置 proxy_pass 的部分添加这样一行。
   * proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   */
  app.use(
    session(
      {
        cookie: { secure: false, maxAge: 86400000 },
      },
      app
    )
  );

  app.proxy = true;
};
